package kmp;

import java.util.Arrays;

public class KMPAlgorithm {
    public static void main(String[] args) {
        String str1 = "BBC ABCDAB ABCDABCDABDE";
        String str2 = "ABCDABD";
        int[] next = getNext(str2);
        System.out.println("next = " + Arrays.toString(next));
        System.out.println("kmpSearch = " + kmpSearch(str1, str2));

    }


    /**
     * KMP算法
     *
     * @param str1
     * @param str2
     * @return
     */
    public static int kmpSearch(String str1, String str2) {
        int[] next = getNext(str2);

        for (int i = 0, j = 0; i < str1.length(); i++) {
            while (j > 0 && str1.charAt(i) != str2.charAt(j)) {
                j = next[j - 1];
            }
            if (str1.charAt(i) == str2.charAt(j)) {
                j++;
            }
            if (j == str2.length()) {
                return i - j + 1;
            }
        }
        return -1;
    }

    public static int[] getNext(String str) {
        int length = str.length();
        int[] next = new int[length];

        //初始化next数组第一位为0
        next[0] = 0;
        for (int i = 1, j = 0; i < length - 1; i++) {

            while (j > 0 && str.charAt(i) != str.charAt(j)) {
                j = next[j - 1];
            }

            if (str.charAt(i) == str.charAt(j)) {
                j++;
            }
            next[i] = j;
        }
        return next;
    }
}
